#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import cgi
import json
import db_conf
import time
con = None

def insert_peak_sql():
    return """INSERT INTO spectral_peak (spectrum_id, mz, intensity) VALUES (%s,%s,%s)"""

def insert_compound_spectrum_sql():
    return """INSERT INTO compound_spectrum (spectrum_id, compound_id, authentic) VALUES (%s,%s,%s)"""

try:
    #print time.asctime( time.localtime(time.time()) )	
    qform = cgi.FieldStorage()
    chromatogram_id = qform.getvalue('chromatogram_id')	    	
    RI = qform.getvalue('sp_ri')
    RT = qform.getvalue('sp_rt')
    resolution = qform.getvalue('sp_resolution')
    spectrum_origin_id = qform.getvalue('spectrum_origin_id')
    spectrum_id = qform.getvalue('spectrum_id')
    compound_id = qform.getvalue('compound_id')
    spectral_comments = qform.getvalue('spectral_comments')
    spectral_peaks = qform.getvalue('spectral_peaks')
    doInsert = 0
    if (spectrum_id == None or spectrum_id == ""):
        doInsert = 1
        insert_spectrum_sql = """INSERT INTO spectrum (chromatogram_id, RI, RT, resolution, spectrum_origin_id, user_comment) VALUES (%s,%s,%s,%s,%s,%s) RETURNING spectrum_id"""    
    else:
        #no use case where spectrums are updated	
        insert_spectrum_sql = ""
    config = db_conf.getConfig('metabvis.conf')
    con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config)) 
    cur = con.cursor()
    if (doInsert):
    	cur.execute(insert_spectrum_sql,(chromatogram_id, RI, RT, resolution, spectrum_origin_id, spectral_comments))
        spectrum_id = str(cur.fetchone()[0])
	#print spectrum_id
        cur.execute(insert_compound_spectrum_sql(),(spectrum_id, compound_id, "Y"))
    peak_lines = spectral_peaks.split("\n")
    cur.execute("commit")
    delimiter = " "
    if (spectral_peaks.find(",") != -1):
        delimiter = ","
    if (spectral_peaks.find("\t") != -1):
        delimiter = "\t"
    for p in peak_lines:
       ptk = p.split(delimiter)
       if (len(ptk) >= 2 ):
           cur.execute(insert_peak_sql(), (str(spectrum_id), ptk[0], ptk[1]))
    cur.execute("commit")     
    print "Content-type: text/html;charset=utf-8\r\n"
    pa = {}
    pa['_spid'] = spectrum_id
    print json.dumps(pa)
except psycopg2.DatabaseError, e:
    print 'Update Error %s' % e    
    sys.exit(1)    
finally:
    if con:
        con.close()
